package com.zzyl.nursing.service.impl;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baidubce.qianfan.util.Json;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.ai.AiInvoker;
import com.zzyl.nursing.dto.HealthAssessmentDto;
import com.zzyl.nursing.vo.HealthAssessmentVo;
import com.zzyl.nursing.vo.HealthReportVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 健康评估Service业务层处理
 * 
 * @author zsn
 * @date 2025-05-20
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService
{
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

    /**
     * 查询健康评估
     * 
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询健康评估列表
     * 
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }



    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AiInvoker aiInvoker;
    /**
     * 新增健康评估
     * 
     * @param dto 健康评估
     * @return 结果
     */
    @Override
    public Long insertHealthAssessment(HealthAssessmentDto dto)
    {
        //1.参数校验,四个参数
        if("null".equals(dto.getIdCard()) || dto.getIdCard().isBlank()){
            throw new BaseException("身份证号不合法");
        }
        if("null".equals(dto.getElderName()) || dto.getElderName().isBlank()){
            throw new BaseException("姓名为空不合法");
        }
        if("null".equals(dto.getPhysicalExamInstitution()) || dto.getPhysicalExamInstitution().isBlank()){
            throw new BaseException("体检机构不合法");
        }
        if("null".equals(dto.getPhysicalReportUrl()) || dto.getPhysicalReportUrl().isBlank()){
            throw new BaseException("体检机构URL链接不合法");
        }
        //2.获取redis中的数据
        String pdfText = (String) redisTemplate.opsForHash().get(CacheConstants.HEALTH_ASSESSMENT_TEXT_KEY, dto.getIdCard());
        if (StringUtils.isBlank(pdfText)){
            throw new BaseException("未上传pdf文件");
        }
        //3.获取模版
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("prompt.txt");
        String template = IoUtil.read(in, StandardCharsets.UTF_8);

        //4.替换模版中的prompt
        String prompt = template.replace("prompt", pdfText);

        //5.使用千帆模型获取数据
        String chat = aiInvoker.invokeQianFanChat(prompt);

        //6.解析获取数据为vo类型
        HealthReportVo healthReportVo = JSON.parseObject(chat, HealthReportVo.class);
        //7.创建HealthAssessMent实例,并封装数据,填入表中
        HealthAssessment healthAssessment = new HealthAssessment();
        //先将部分数据拷贝到HealthAssessMent实例中
        BeanUtils.copyProperties(dto,healthAssessment);
        healthAssessment.setBirthDate(IdcardUtil.getBirthDate(dto.getIdCard()).toLocalDateTime());
        healthAssessment.setAge(IdcardUtil.getAgeByIdCard(dto.getIdCard()));
        healthAssessment.setGender(IdcardUtil.getGenderByIdCard(dto.getIdCard()));
        healthAssessment.setHealthScore(String.valueOf(healthReportVo.getHealthAssessment().getHealthIndex()));
        healthAssessment.setTotalCheckDate(healthReportVo.getTotalCheckDate());
        healthAssessment.setRiskLevel(healthReportVo.getHealthAssessment().getRiskLevel());

        healthAssessment.setReportSummary(healthReportVo.getSummarize());

        healthAssessment.setDiseaseRisk(JSON.toJSONString(healthReportVo.getRiskDistribution()));
        healthAssessment.setAbnormalAnalysis(JSON.toJSONString(healthReportVo.getAbnormalData()));
        healthAssessment.setSystemScore(JSON.toJSONString(healthReportVo.getSystemScore()));

        healthAssessment.setSuggestionForAdmission(healthReportVo.getHealthAssessment().getHealthIndex()>=60?0:1);
        if(healthReportVo.getHealthAssessment().getHealthIndex()>=90){
            healthAssessment.setNursingLevelName("三级护理");
        } else if (healthReportVo.getHealthAssessment().getHealthIndex()>=80) {
            healthAssessment.setNursingLevelName("二级护理");
        } else if (healthReportVo.getHealthAssessment().getHealthIndex()>=70) {
            healthAssessment.setNursingLevelName("一级护理");
        } else if (healthReportVo.getHealthAssessment().getHealthIndex()>=60) {
            healthAssessment.setNursingLevelName("特级护理");
        } else {
            healthAssessment.setNursingLevelName("不允许护理");
        }
        healthAssessment.setAdmissionStatus(0);
        healthAssessment.setAssessmentTime(LocalDateTime.now());

        boolean saveResult = this.save(healthAssessment);
        if (!saveResult){
            throw new BaseException("新增数据失败");
        }

        //8.删除缓存中的数据
        redisTemplate.opsForHash().delete(CacheConstants.HEALTH_ASSESSMENT_TEXT_KEY,dto.getIdCard());

        //9.返回数据
        return healthAssessment.getId();
    }

    /**
     * 修改健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment)
    {
        return updateById(healthAssessment) ? 1 : 0;
    }

    /**
     * 批量删除健康评估
     * 
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除健康评估信息
     * 
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }
}
